﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.IO;
using System.Windows.Forms;

namespace drawDong
{
    public static class WriteWorker
    {
        private static ArrayList replaceContentList = new ArrayList();
        private static bool isAdding = false;
        private static int i = 0;
        public class RepContent
        {
            public string path;
            public string contentStr;
        }

        public static void add(RepContent rc)
        {
            lock (replaceContentList.SyncRoot)
            {
                replaceContentList.Add(rc);
            }
            if (isAdding) {
                return;
            }
            new System.Threading.Thread(appendContent).Start();
        }

        public static void AddRange(ArrayList ar)
        {
            lock (replaceContentList.SyncRoot)
            {
                replaceContentList.AddRange(ar);
            }
            if (isAdding)
            {
                return;
            }
            new System.Threading.Thread(appendContent).Start();
        }

        private static void appendContent()
        {
            Console.WriteLine("开始写入");
            Console.WriteLine(DateTime.Now.ToLocalTime().ToString());
            isAdding = true;
            while (replaceContentList.Count > 0)
            {
                RepContent rc;
                lock (replaceContentList.SyncRoot)
                {
                    rc = (RepContent)replaceContentList[0];
                    replaceContentList.RemoveAt(0);
                }
                StreamWriter streamwriter = new StreamWriter(rc.path, true);
                try
                {
                    streamwriter.WriteLineAsync(rc.contentStr);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                finally
                {
                    streamwriter.Flush();
                    streamwriter.Close();
                    streamwriter.Dispose();
                }
                ++i;
            }
            isAdding = false;
            
            Console.WriteLine(i);
            i = 0;
            Console.WriteLine(DateTime.Now.ToLocalTime().ToString());
            Console.WriteLine("写入完毕");
        }
    }


    

}
